package drds.global_transaction.api.message_codec.request_and_response.transaction.global_transaction.global_transaction_begin;

import drds.global_transaction.api.message_codec.Message;
import drds.global_transaction.api.message_codec.request_and_response.transaction.TransactionResponse;
import lombok.Getter;
import lombok.Setter;

import java.nio.ByteBuffer;

public class GlobalTransactionBeginResponseMessage extends TransactionResponse
{
	private static final long serialVersionUID = -1L;
	@Setter
	@Getter
	private String globalTransactionIdWithAddressAndPort;
	@Setter
	@Getter
	private String extraData;

	@Override
	public void decode(ByteBuffer byteBuffer)
	{
		super.decode(byteBuffer);

		short length = byteBuffer.getShort();
		if (length > 0)
		{
			byte[] bytes = new byte[length];
			byteBuffer.get(bytes);
			setGlobalTransactionIdWithAddressAndPort(new String(bytes, UTF8));
		}

		length = byteBuffer.getShort();
		if (length > 0)
		{
			byte[] bytes = new byte[length];
			byteBuffer.get(bytes);
			setExtraData(new String(bytes, UTF8));
		}
	}

	@Override
	public short getTypeCode()
	{
		return Message.global_transaction_begin_response_message;
	}

	@Override
	public ByteBuffer putBytesToByteBuffer()
	{
		ByteBuffer byteBuffer = super.putBytesToByteBuffer();

		if (this.globalTransactionIdWithAddressAndPort != null)
		{
			byte[] bytes = globalTransactionIdWithAddressAndPort.getBytes(UTF8);
			byteBuffer.putShort((short) bytes.length);
			if (bytes.length > 0)
			{
				byteBuffer.put(bytes);
			}
		} else
		{
			byteBuffer.putShort((short) 0);
		}

		if (this.extraData != null)
		{
			byte[] bytes = extraData.getBytes(UTF8);
			byteBuffer.putShort((short) bytes.length);
			if (bytes.length > 0)
			{
				byteBuffer.put(bytes);
			}
		} else
		{
			byteBuffer.putShort((short) 0);
		}
		markAsEncode();
		return byteBuffer;
	}
}
